# coding=utf-8
from __future__ import division

from django.template import Template
from django.template import Context
from django.core.paginator import *

from google.appengine.api import users
from google.appengine.ext import db

from blog.models import Category
from blog.models import Diary
from blog.models import Tag
from blog.models import Comment
from link.models import Link

from helper import rand_color 

category_list = '''
    {% load blog_extras %}
    <ul class="sidemenu">
        {% for category in categories %}
        <li>
            <a href="/blog/category/{{category|id}}/">{{category.name}}({{category.diary_set|count}})</a>
            {% if is_user_admin %}
            <div id="delete_category_{{category|id}}" class="delete_icon"></div>
            {% endif %}
            <div class="clear"/>
        </li>
        {% endfor %}
    </ul>
    '''
    
tag_list = '''
    {% load blog_extras %}
    <div class="sidemenu, tag_cloud">
        {% for tag in tags %}
            {% autoescape off %}{{tag}}{% endautoescape %}
        {% endfor %}
    </div>
'''    
    
link_list = '''
    {% load blog_extras %}
    <ul class="sidemenu">
        {% for link in links %}
        <li>
            <a href="{{link.url}}" target="_blank">{{link.title}}</a>
            {% if is_user_admin %}
            <div id="delete_link_{{link|id}}" class="delete_icon"></div>
            {% endif %}
            <div class="clear"/>
        </li>
        {% endfor %}
    </ul>
'''

comment_list = '''
{% load blog_extras %}
{% for comment in comments %}
<p class="comment_summary">{{comment.content}}</p>
{% endfor %}
'''

diary_list = '''
    {% load blog_extras %}
    {% if diarys.object_list|length_is:"0" %}
                暂时还没有日志，谢谢关注！
    {% else %}
        {% for diary in diarys.object_list %}
        <a href="/blog/diary/{{diary|id}}/">
            <h1>{{diary.title}}</h1>
        </a>
        {% autoescape off %}<div class="diary_summary">{{diary.content}}</div>{% endautoescape %}
        <div class="post-footer align-left">
            <div style="float:left;">标签：
            {% for tag in diary.tags_set %}
                <a href="/blog/tag/{{tag|id}}/">{{tag.name}} </a> {% if not forloop.last %} | {% endif %}
            {% endfor %}
            </div>
            <div style="float:right;">
                <a href="/blog/diary/{{diary|id}}/#comment" class="comments">评论({{diary.comment_set|count}})</a>
                <span class="read_count">点击次数：{{diary.read_count}}</span>
                <span class="date">{{diary.post_time|date:"Y-m-d H:i"}}</span>
                {% if is_user_admin %}
                <div id="delete_diary_{{diary|id}}" class="delete_icon"></div>
                <div id="edit_diary_{{diary|id}}" class="edit_icon"></div>
                {% endif %}
            </div>
            <div style="clear:both;"></div>
        </div>
        <div style="clear:both;"></div>
        {% endfor%}
        <div class="pagination">
            <span class="step-links">
                                            共{{diarys.paginator.num_pages}}页|
                {% ifnotequal diarys.number 1 %}<a href="/blog/1/">第一页</a>{% endifnotequal %}
                {% ifequal diarys.number 1 %}第一页{% endifequal %}
                
                {% if diarys.has_previous %}<a href="/blog/{{ diarys.previous_page_number }}/">上一页</a>{% endif %}
                {% if not diarys.has_previous %}上一页 {% endif %}
                
                {% for index in diarys.paginator.page_range%}
                    {% ifequal diarys.number index%}
                        [{{index}}]
                    {% endifequal%}
                    {% ifnotequal diarys.number index%}
                        <a href="/blog/{{ index }}/">[{{index}}]</a>
                    {% endifnotequal%}
                {% endfor %}
                
                {% if diarys.has_next %}<a href="/blog/{{ diarys.next_page_number }}/">下一页</a>{% endif %}
                {% if not diarys.has_next %}下一页 {% endif %}
                
                {% ifnotequal diarys.number diarys.paginator.num_pages %}<a href="/blog/{{diarys.paginator.num_pages}}/">最末页</a>{% endifnotequal %}
                {% ifequal diarys.number diarys.paginator.num_pages %}最末页{% endifequal %}
            </span>
        </div>
    {% endif %}
'''

diary_template = '''
{% load blog_extras %}
<a href="/blog/diary/{{diary|id}}/">
    <h1>{{diary.title}}</h1>
</a>
{% autoescape off %}<div>{{diary.content}}</div>{% endautoescape %}
<div class="post-footer align-left">
    <div style="float:left;">标签：
    {% for tag in diary.tags_set %}
        <a href="/blog/tag/{{tag|id}}/">{{tag.name}} </a> {% if not forloop.last %} | {% endif %}
    {% endfor %}
    </div>
    <div style="float:right;">
        <a href="#comment" class="comments">评论({{diary.comment_set|count}})</a>
        <span class="read_count">点击次数：{{diary.read_count}}</span>
        <span class="date">{{diary.post_time|date:"Y-m-d H:i"}}</span>
        {% if is_user_admin %}
        <div id="delete_diary_{{diary|id}}" class="delete_icon"></div>
        {% endif %}
    </div>
    <div style="clear:both;"></div>
</div>
<div style="clear:both;"></div>
<div id="comments" >
    <a name="comment"></a>
    <label>评论&nbsp;&nbsp;&nbsp;&nbsp;<input style="float:" id="add_comment_{{diary|id}}" class="button" type="button" value="我也评论"/></label>
    {% for comment in diary.comment_set%}
    <div class="comment">
        <div class="comment_head"><a href="mailto:{{comment.email}}">{{comment.nick_name}}({{comment.author}})</a>发表于<span class="date" style="float:none;">{{comment.post_time|date:"Y-m-d H:i"}}</span></div>
        <p>{{comment.content}}</p>
    </div>
    {% endfor %}
</div>
'''

comment_form_template = '''
<form id="add_comment_form" method="POST">
    <input type="hidden" name="diary_id" value="{{diary_id}}" />
    <p>
        <label>姓名：</label>
        <input id="id_nick_name" name="nick_name" value="{{login_user.nickname}}" type="text" size="30" />
    </p>
    <p>
        <label>Email：</label>
        <input id="id_email" name="email" value="{{login_user.email}}" type="text" size="30" />
    </p>
    <p>
        <label>我想说：</label>
        <textarea id="id_content" name="content"></textarea>
    </p>
</form>
'''

def gen_category_list_html():
    categories = Category.all()
    tmp = Template(category_list)
    ctx = Context({'categories':categories, 
                   'is_user_admin':users.is_current_user_admin(),
                   })
    return tmp.render(ctx)

def gen_link_list_html():
    link = Link.all()
    tmp = Template(link_list)
    ctx = Context({'links':link, 
                   'is_user_admin':users.is_current_user_admin(),
                   })
    return tmp.render(ctx)

def gen_diary_list_html(p_id, c_id=None, t_id=None):
    if c_id:
        category = db.get(c_id)
        diarys_all = category.diary_set.order('-post_time')
    elif t_id:
        d_ids = db.get(t_id).diaries
        diarys_all = [db.get(d_id) for d_id in d_ids]
    else:
        diarys_all = Diary.all().order('-post_time')
        
    paginator = Paginator(diarys_all, 8)
    
    try:
        page_index = int(p_id)
    except (ValueError, TypeError):
        page_index = 1
    
    try:
        diarys = paginator.page(page_index)
    except (EmptyPage, InvalidPage):
        diarys = paginator.page(paginator.num_pages)
    
    tmp = Template(diary_list)
    ctx = Context({'diarys':diarys, 
                   'is_user_admin':users.is_current_user_admin(),
                   })
    return tmp.render(ctx)

def gen_diary_html(diary_id):
    try:
        diary = Diary.get(diary_id)
        diary.read_count = diary.read_count + 1
        diary.put()
        ctx = Context({'diary':diary,})
        tmp = Template(diary_template)
        return tmp.render(ctx)
    except:
        return "没有找到相应日志，该日志已经被删除或者您输入的URL错误。"
    

def gen_tag_list_html():
    tags = Tag.all()
    tag_weighing = [len(tag.diaries) for tag in tags]
    tag_strs = ""
    if(len(tag_weighing) != 0):
        max_w = max(tag_weighing)
        min_w = min(tag_weighing)
        weighing = float(3/((max_w - min_w) + 1))
        tag_strs = [];
        for tag in tags:
            font_size = str(weighing * len(tag.diaries) + 12) + "px";
            color = rand_color()
            tag_strs.append("<a href='/blog/tag/" + str(tag.key()) + "/' style='color:" + color + ";font-size:" + font_size + ";'>" + tag.name + "</a>&nbsp;&nbsp;")
    
    tmp = Template(tag_list)
    ctx = Context({'tags':tag_strs})
    return tmp.render(ctx)

def gen_comment_form(diary_id):
    tmp = Template(comment_form_template)
    ctx = Context({'diary_id':diary_id,
                   'login_user':users.get_current_user()})
    return tmp.render(ctx)

def gen_comment_list_html():
    comments = Comment.all().order('-post_time')[:4]
    tmp = Template(comment_list)
    ctx = Context({'comments':comments})
    return tmp.render(ctx)